package com.shimao.celnet.payment.controller;

import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.util.AliyunOSSClientUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/upImg")
public class OSSController {
    /**
     * OSS上传文件
     *
     * @throws Exception
     */
    @RequestMapping(value = "/user/authorize", method = RequestMethod.POST)
    public String uploadImg(@RequestParam("file") MultipartFile file,
                            @RequestParam("userId") String userId,
                            HttpServletRequest req, HttpServletResponse res) throws Exception {
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");//初始化错误码和错误信息
        try {
            if (file == null || file.getSize() <= 0) {
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS,"缺少图片");
            }
            String name = AliyunOSSClientUtil.uploadImg2Oss(file);
            String imgUrl = AliyunOSSClientUtil.getImgUrl(name);//图片路径
            retJson.addBody("userId",userId);
            retJson.addBody("img", imgUrl);
        } catch (IOException e) {
            retJson.addBody("img", "");
        }
        return retJson.toString();
    }
}
